mod route;
use axum::{
    extract::Request,
    http::{HeaderMap, StatusCode},
    middleware::{self, Next},
    response::Response,
    routing::{get, post},
    Router,
};
use route::{parse_project, transpile_file, transpile_project};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
extern crate c2rust002;

async fn auth_middleware(
    //run the `HeaderMap` extractor
    headers: HeaderMap,
    //you can also add more extractors here but the last
    //extractor must implement `FromRequest` which
    //`Request` does
    request: Request,
    next: Next,
) -> Result<Response, StatusCode> {
    match get_token(&headers) {
        Some(token) if token_is_valid(token) => {
            let response = next.run(request).await;
            Ok(response)
        }
        _ => Err(StatusCode::UNAUTHORIZED),
    }
}
//
fn get_token(_headers: &HeaderMap) -> Option<&str> {
    Some("token")
}
//
fn token_is_valid(_token: &str) -> bool {
    true
}
// 示例路由处理函数
async fn hello_world() -> &'static str {
    "Hello, World!"
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Project {
    name: String,
    directories: Option<Vec<Directory>>,
    files: Option<Vec<File>>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Directory {
    name: String,
    path: String,
    directories: Option<Vec<Directory>>,
    files: Option<Vec<File>>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct File {
    name: String,
    content: String,
    path: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct ParseProject {
    pub project: Project,
}

#[tokio::main]
async fn main() {
    dotenv::dotenv().ok();
    // 创建路由
    let app = Router::new()
        .route("/", get(hello_world))
        .route("/parse_project", post(parse_project))
        .route("/transpile_project", post(transpile_project))
        .route("/transpile_file", post(transpile_file))
        .route_layer(middleware::from_fn(auth_middleware));

    // 设置服务地址
    let addr = SocketAddr::from(([0, 0, 0, 0], 9900));
    println!("Server running on http://{}", addr);

    // 启动服务器
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
